package org.springblade.auth.controller;

import com.babble.user.entity.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.auth.granter.TokenParameter;
import org.springblade.auth.secure.AuthInfo;
import org.springblade.auth.utils.WebTokenUtil;
import org.springblade.auth.webGranter.WebTokenGranter;
import org.springblade.auth.webGranter.WebTokenGranterBuilder;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
@RequestMapping("babble")
@Api(value = "WEB用户授权认证", tags = "授权接口")
public class WebAuthController {

	@PostMapping("token")
	@ApiOperation(value = "WEB认证token", notes = "账号:account,密码:password;第三方授权:social;重置token:refresh_token")
	public R<AuthInfo> token(@ApiParam(value = "授权类型(password,refresh_token,social)", required = true) @RequestParam(defaultValue = "password", required = false) String grantType,
							 @ApiParam(value = "刷新令牌") @RequestParam(required = false) String refreshToken,
							 @ApiParam(value = "账号") @RequestParam(required = false) String account,
							 @ApiParam(value = "密码") @RequestParam(required = false) String password) {

		String userType = Func.toStr(WebUtil.getRequest().getHeader(WebTokenUtil.USER_TYPE_HEADER_KEY), WebTokenUtil.DEFAULT_USER_TYPE);

		TokenParameter tokenParameter = new TokenParameter();
		tokenParameter.getArgs()
			.set("account", account)
			.set("password", password)
			.set("grantType", grantType)
			.set("refreshToken", refreshToken)
			.set("userType", userType);

		WebTokenGranter granter = WebTokenGranterBuilder.getGranter(grantType);
		UserInfo userInfo = granter.grant(tokenParameter);

		if (userInfo == null || userInfo.getUser() == null || userInfo.getUser().getId() == null) {
			return R.fail(WebTokenUtil.USER_NOT_FOUND);
		}
		return R.data(WebTokenUtil.createAuthInfo(userInfo));
	}
}
